//
//  TMTabbarView.swift
//  TimMusic
//
//  Created by nkl on 2024/10/10.
//

import Foundation
import Kingfisher
import TSVideoKit
import UIKit

protocol TMTabBarDelegate: AnyObject {
    func didSelectedTabbarItem(idx: Int)
}

class TMTabBar: UIView {
    lazy var playBtn: TMTabbarPlayView = TMTabbarPlayView()

    lazy var hStack: UIStackView = {
        let stack = UIStackView.hStack
        stack.backgroundColor = .black
        stack.layer.cornerRadius = tabbarHeight / 2.0
        stack.layer.masksToBounds = true
        return stack
    }()

    lazy var musicItem: TMTabBarItem = {
        createTabBarItem(imageNormal: "ic_tab_music_normal",
                         imageSelected: "ic_tab_music_selected",
                         title: "Music",
                         isSelected: true, tag: 0)
    }()

    lazy var widgetItem: TMTabBarItem = {
        createTabBarItem(imageNormal: "ic_tab_widget_normal",
                         imageSelected: "ic_tab_widget_selected",
                         title: "Widget",
                         isSelected: false, tag: 1)
    }()

    lazy var settingItem: TMTabBarItem = {
        createTabBarItem(imageNormal: "ic_tab_setting_normal",
                         imageSelected: "ic_tab_setting_selected",
                         title: "Setting",
                         isSelected: false, tag: 2)
    }()

    weak var delegate: TMTabBarDelegate?

    private var items: [TMTabBarItem] {
        [musicItem, widgetItem, settingItem]
    }

    func updateTime(time: String) {
        playBtn.timeLabel.text = time
    }

    func updateState(isPlaying: Bool) {
        playBtn.pauseButton.isSelected = isPlaying
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        addChildren()
        makeConstraints()
    }

    func changeStatus(show: Bool) {
        if show {
            playBtn.icBgView.isHidden = true
            playBtn.timeLabel.isHidden = true
            playBtn.pauseButton.isHidden = true
        } else {
            playBtn.icBgView.isHidden = false
            playBtn.timeLabel.isHidden = false
            playBtn.pauseButton.isHidden = false
        }
    }

    func addChildren() {
        addSubview(playBtn)
        addSubview(hStack)
        hStack.addArrangedSubview(musicItem)
        hStack.addArrangedSubview(widgetItem)
        hStack.addArrangedSubview(settingItem)
        startRotationAnimation()
    }

    func startRotationAnimation() {
        // 检查是否已经有旋转动画
        guard playBtn.iconButton.layer.animation(forKey: "rotationAnimation") == nil else { return }

        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotationAnimation.toValue = NSNumber(value: Double.pi * 2) // 旋转一圈
        rotationAnimation.duration = 5 // 每圈的持续时间
        rotationAnimation.isCumulative = true
        rotationAnimation.repeatCount = Float.infinity // 无限重复

        playBtn.iconButton.layer.add(rotationAnimation, forKey: "rotationAnimation")
    }

    // 可以添加一个停止旋转的方法
    func stopRotating() {
        if playBtn.iconButton.layer.animation(forKey: "rotationAnimation") != nil {
            playBtn.iconButton.layer.removeAnimation(forKey: "rotationAnimation")
        }
    }

    func updateVideoImage(video: TSVideo) {
        if let imagedata = video.artwork, let img = UIImage(data: imagedata) {
            playBtn.iconImage.image = img

        } else {
            playBtn.iconImage.kf.setImage(with: video.iconUrl)
        }
    }

    func makeConstraints() {
        playBtn.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
        }
        hStack.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-16)
            make.centerY.equalToSuperview()
        }

        musicItem.snp.makeConstraints { make in
            make.width.equalTo(82)
            make.height.equalTo(tabbarHeight)
        }

        widgetItem.snp.makeConstraints { make in
            make.width.equalTo(82)
            make.height.equalTo(tabbarHeight)
        }

        settingItem.snp.makeConstraints { make in
            make.width.equalTo(82)
            make.height.equalTo(tabbarHeight)
        }
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func createTabBarItem(imageNormal: String, imageSelected: String, title: String, isSelected: Bool, tag: Int) -> TMTabBarItem {
        let btn = TMTabBarItem()
        btn.setImage(UIImage(named: imageNormal), for: .normal)
        btn.setImage(UIImage(named: imageSelected), for: .selected)
        btn.setTitle(title, for: .selected)
        btn.setTitle("", for: .normal)
        btn.titleLabel?.font = .systemFont12
        btn.setTitleColor(.black, for: .selected)
        btn.setTitleColor(.white, for: .normal)
        btn.layer.cornerRadius = tabbarHeight / 2.0
        btn.layer.masksToBounds = true
        btn.isSelected = isSelected
        btn.tag = tag
        btn.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
        return btn
    }

    @objc func buttonAction(sender: TMTabBarItem) {
        for item in items {
            item.isSelected = false
        }
        sender.isSelected = true
        delegate?.didSelectedTabbarItem(idx: sender.tag)
    }
}
